package org.example.zhihuan.control;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.zhihuan.services.Complaint;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "ComplaintServlet", urlPatterns = "/complaint")
    public class ComplaintServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Content-Type", "application/json;charset=UTF-8");

        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
        Map<String, Object> map = mapper.readValue(req.getInputStream(), HashMap.class);
        try {
            switch (map.get("_type").toString()) {
                case "list":
                    listComplain(map, resp);
                    break;
                default:
                    resp.getWriter().print(new Result(999, "未知", null));
            }
        } catch (Exception e) {
            resp.getWriter().print(new Result(432, e.getMessage(), null));
        }
    }

    private void listComplain(Map<String, Object> map, HttpServletResponse resp) throws IOException {
        if (!(map.containsKey("pageCount") && map.containsKey("pageNumber"))) {
            resp.getWriter().print(new Result(432, "缺少页面设置", null));
            return;
        }
        Map<String, Object> m = Complaint.getList(map);
        Result result = Result.ok(m);
        resp.getWriter().print(result);
    }

}
